package com.seelyn.rhea.mvc.internal;

import com.seelyn.rhea.mvc.context.Session;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author slacrey
 * @since 2016/1/23
 */
public class InternalSession implements Session, Serializable {

    private static final long serialVersionUID = 1504908578686072629L;
    private final HttpSession session;

    public InternalSession(HttpSession session) {
        if (session == null) {
            throw new IllegalArgumentException("session cannot be null");
        }
        this.session = session;
    }

    @Override public HttpSession raw() {
        return session;
    }

    @Override @SuppressWarnings("unchecked")
    public <T> T attribute(String name) {
        return (T) session.getAttribute(name);
    }

    @Override public void attribute(String name, Object value) {
        session.setAttribute(name, value);
    }

    @Override public Set<String> attributes() {
        Set<String> attributes = new TreeSet<>();
        Enumeration<String> enumeration = session.getAttributeNames();
        while (enumeration.hasMoreElements()) {
            attributes.add(enumeration.nextElement());
        }
        return attributes;
    }

    @Override public long creationTime() {
        return session.getCreationTime();
    }

    @Override public String id() {
        return session.getId();
    }

    @Override public long lastAccessedTime() {
        return session.getLastAccessedTime();
    }

    @Override public int maxInactiveInterval() {
        return session.getMaxInactiveInterval();
    }

    @Override public void maxInactiveInterval(int interval) {
        session.setMaxInactiveInterval(interval);
    }

    @Override public void invalidate() {
        session.invalidate();
    }

    @Override public boolean isNew() {
        return session.isNew();
    }

    @Override public void removeAttribute(String name) {
        session.removeAttribute(name);
    }

}
